package cn.kgc.shiro01.shiro;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import java.util.Arrays;
import java.util.List;

/**
 * @Author: 课工场
 * @Version: v1.0  2023/3/31
 * @Description:   用户自定义域对象  实现数据的持久层操作
 */
public class CustomerRealm extends AuthorizingRealm {

    //授权方法   用户访问受限资源时  doGetAuthorizationInfo
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        // 当前用户的用户名
        String primaryPrincipal = (String) principals.getPrimaryPrincipal();
        // 1. TODO 查询数据库 查询当前用户是否具有哪些权限  RBAC    基于角色  基于权限字符串
        System.out.println("=============doGetAuthorizationInfo==================");
        // 2. 将从数据库中查询的角色信息 权限字符串信息 封装成 AuthorizationInfo
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();

        List<String> roles = Arrays.asList("admin", "super");
        //simpleAuthorizationInfo.addRole("super");
        simpleAuthorizationInfo.addRoles(roles);  // admin  super

        //设置权限字符串
        //List<String> permissions = Arrays.asList("user:delete", "user:update");
        simpleAuthorizationInfo.addStringPermission("user:*");
        //simpleAuthorizationInfo.addStringPermissions(permissions);

        return simpleAuthorizationInfo;
    }


    // 认证方法  login(token)
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("==============CustomerRealm 中认证的方法doGetAuthenticationInfo  被调用================");
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
        String username = usernamePasswordToken.getUsername();
        // TODO  根据用户名 查询用户信息  如果用户信息存在  将用户信息进行封装  AuthenticationInfo   ->SimpleAuthenticationInfo
        if("tom".equals(username)){
            //SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo("tom", "eeb9bad681184779aa6570e402d6ef6c", this.getName());
            //SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo("tom", "eeb9bad681184779aa6570e402d6ef6c", ByteSource.Util.bytes("hello"),this.getName());
            SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo("tom", "789158baeb148949fb68959ce17bf65d", ByteSource.Util.bytes("hello"),this.getName());

            return  simpleAuthenticationInfo;
        }
        return null;
    }
}
